//
//  RSDB.m
//
//  Created by Johnnie Walker on 10/07/2008.
//  Copyright 2008 Random Sequence. All rights reserved.
//

#import "RSDB.h"

@implementation RSDB

static RSDBDatabase *defaultDatabase = nil;
static NSMutableDictionary *tables;

+(NSArray *)argumentsFromSQL:(NSString *)sql args:(va_list)args
{
    int argsCount = sqlite3_bind_parameter_count([[[self defaultDatabase] statementFromSQL:sql] statement]);	
	NSMutableArray *argsArray = [NSMutableArray arrayWithCapacity:argsCount];
	id arg;	
	unsigned i;
	for	(i=0; i<argsCount; i++) {
		arg = va_arg(args, id);
        if (!arg) {
            break;
        }						
		[argsArray addObject:arg];
	}	
	return argsArray;
}

+ (void)setDefaultDatabase:(RSDBDatabase *)aDatabase
{
	if ([aDatabase isEqual:defaultDatabase]) {
		return;
	}
	
	[aDatabase retain];
	[defaultDatabase release];
	defaultDatabase = aDatabase;
}

+ (RSDBDatabase *)defaultDatabase
{
	return defaultDatabase;
}

+(RSDBTable *)getTable:(NSString *)tableName
{
	return [RSDB getTable:tableName database:[RSDB defaultDatabase]];
}

+(void)flushTables
{
	[tables release];
	tables = nil;
}

+(RSDBTable *)getTable:(NSString *)tableName database:(RSDBDatabase *)database;
{	
//	if ([RSDB defaultDatabase] == nil && database != nil) {
//		[RSDB setDefaultDatabase:database];
//	}
	
	if (database == nil) {
		database = [RSDB defaultDatabase];
	}
	
	if (database == nil) {
		#ifdef DEBUG_BUILD
		NSLog(@"No database specified for getTable or no default database set");
		#endif
		return nil;
	}	
	
	if (nil == tables) {
		tables = [[NSMutableDictionary alloc] init]; 
	}

//	NSLog(@"tables: %@",tables);
	
	if (nil == [tables objectForKey:database.databaseURL]) {
		[tables setObject:[NSMutableDictionary dictionary] forKey:database.databaseURL];
	}

//	NSLog(@"tables: %@",tables);
	
	if (nil == [[tables objectForKey:database.databaseURL] objectForKey:tableName]) {
		if ([database tableExists:tableName]) {
			[[tables objectForKey:database.databaseURL] setObject:[[[RSDBTable alloc] initWithTableName:tableName database:database] autorelease] forKey:tableName];
		}
	}
	
//	NSLog(@"tables: %@",tables);	
	
	return [[tables objectForKey:database.databaseURL] objectForKey:tableName];
}

@end
